﻿using System;
using System.Collections.Generic;
using System.Text;
using SlimDX.Direct3D9;

namespace SlimWater
{
    class XMesh
    {
        public Mesh mesh;
        public Material[] materials;
        public Texture[] textures;

        private Device device;

        public XMesh(Device device, string filename)
        {
            this.device = device;

            mesh = Mesh.FromFile(device, "../../data/" + filename, MeshFlags.Managed);
            mesh.ComputeNormals();
            ExtendedMaterial[] materialArray = mesh.GetMaterials();

            if ((materialArray != null) && (materialArray.Length > 0))
            {
                materials = new Material[materialArray.Length];
                textures = new Texture[materialArray.Length];

                for (int i = 0; i < materialArray.Length; i++)
                {
                    materials[i] = materialArray[i].MaterialD3D;
                    materials[i].Ambient = materials[i].Diffuse;

                    if ((materialArray[i].TextureFileName != null) && (materialArray[i].TextureFileName != string.Empty))
                    {
                        textures[i] = Texture.FromFile(device, "../../data/" + materialArray[i].TextureFileName);
                    }
                }
            }
        }

        public virtual void Render()
        {
            for (int i = 0; i < materials.Length; i++)
            {
                device.Material = materials[i];
                device.SetTexture(i, textures[i]);
                mesh.DrawSubset(i);
            }
        }
    }
}
